﻿using System;
using System.Collections.Generic;
using System.Linq;
using BFlatCompile.Nodes;

namespace BFlatCompile.Serializer
{
	internal static class Phase04FlattenNamespaces
	{
		public static Namespace[] Do(Namespace[] rootNamespaces)
		{
			List<Namespace> namespaces = new List<Namespace>();

			foreach (Namespace ns in rootNamespaces)
			{
				namespaces.AddRange(GatherAllNamespaces(ns));
			}

			for (int i = 0; i < namespaces.Count; ++i)
			{
				namespaces[i].ID = i + 1;
			}

			return namespaces.ToArray();
		}

		private static List<Namespace> GatherAllNamespaces(Namespace ns)
		{
			List<Namespace> namespaces = new List<Namespace>() { ns };
			foreach (Namespace sns in ns.Namespaces)
			{
				namespaces.AddRange(GatherAllNamespaces(sns));
			}
			return namespaces;
		}
	}
}
